// 保存文件分片
import {mkdirSync, writeFileSync} from 'node:fs';
import path from 'node:path';
import {randomUUID} from 'node:crypto';
import CryptoJS from 'crypto-js';
import {RSA_IV, RSA_KEY} from '../../constant.ts';
import {IMG_PATH} from '../constant.ts';

// 文件名称，piece列表
const pieceMap = new Map<string, string[]>();

export default function saveFilePiece(res: FormData) {
  const data = res.get('data') as string;
  const index = +(res.get('index') as string);
  const total = +(res.get('total') as string);
  const fileName = res.get('filename') as string ?? `${randomUUID()}.png`;

  if (!pieceMap.has(fileName)) pieceMap.set(fileName, []);
  const pieceList = pieceMap.get(fileName);
  pieceList[index] = data;

  // 未传输完成，退出
  if (pieceList.filter(i => i).length !== total) return;

  // 已传输完成，保存文件
  pieceMap.delete(fileName);
  const totalData = pieceList.join('');

  mkdirSync(IMG_PATH, {recursive: true});
  const filePath = path.join(IMG_PATH, fileName);
  const bytes = CryptoJS.AES.decrypt(totalData, CryptoJS.enc.Utf8.parse(RSA_KEY), {
    iv: CryptoJS.enc.Utf8.parse(RSA_IV),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  const base64Data = bytes.toString(CryptoJS.enc.Utf8).replace(/^data:image\/\w+;base64,/, '');
  const dataBuffer = Buffer.from(base64Data, 'base64');
  writeFileSync(filePath, dataBuffer);
}